

package com.hazelcast.internal.yaml;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Used to convert YAML configurations from their {@link YamlMapping} representation to their equivalent {@link JSONObject}
 * representation. It is necessary to convert the configuration written in YAML syntax against a JSON schema.
 */
public final class YamlToJsonConverter {

    private YamlToJsonConverter() {
        // util class
    }

    public static Object convert(YamlNode yamlNode) {
        if (yamlNode == null) {
            return JSONObject.NULL;
        }
        if (yamlNode instanceof YamlMapping yamlMapping) {
            JSONObject resultObject = new JSONObject();
            for (YamlNameNodePair pair : yamlMapping.childrenPairs()) {
                resultObject.put(pair.nodeName(), convert(pair.childNode()));
            }
            return resultObject;
        } else
            if (yamlNode instanceof YamlSequence yamlSequence) {
                JSONArray resultArray = new JSONArray();
                for (YamlNode child : yamlSequence.children()) {
                    resultArray.put(convert(child));
                }
                return resultArray;
            } else
                if (yamlNode instanceof YamlScalar scalar) {
                    return scalar.nodeValue();
                }
        throw new IllegalArgumentException("Unknown type " + yamlNode.getClass().getName());
    }
}
